package com.company.beauty.geo.util;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * 距离计算
 *
 * @author youyoukele
 * @version 1.0
 * @date 2024/04/22
 */
public interface DistanceCalculator {

    double EARTH_RADIUS = 6371.0;

    /**
     * 计算距离
     *
     * @param lat1 纬度1
     * @param lon1 经度1
     * @param lat2 纬度2
     * @param lon2 经度2
     * @return 返回 xx km
     */
    static BigDecimal calculateDistance(String lat1, String lon1, String lat2, String lon2) {
        return calculateDistance((new BigDecimal(lat1)).doubleValue(), (new BigDecimal(lon1)).doubleValue(), (new BigDecimal(lat2)).doubleValue(), (new BigDecimal(lon2)).doubleValue());
    }

    /**
     * 计算距离
     *
     * @param lat1 纬度1
     * @param lon1 经度1
     * @param lat2 纬度2
     * @param lon2 经度2
     * @return 返回 xx km
     */
    static BigDecimal calculateDistance(double lat1, double lon1, double lat2, double lon2) {
        double radLat1 = Math.toRadians(lat1);
        double radLon1 = Math.toRadians(lon1);
        double radLat2 = Math.toRadians(lat2);
        double radLon2 = Math.toRadians(lon2);
        double dlon = radLon2 - radLon1;
        double dlat = radLat2 - radLat1;
        double a = Math.pow(Math.sin(dlat / 2.0), 2.0) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(dlon / 2.0), 2.0);
        double c = 2.0 * Math.atan2(Math.sqrt(a), Math.sqrt(1.0 - a));
        double distance = 6371.0 * c;
        return (new BigDecimal(distance)).setScale(3, RoundingMode.HALF_UP);
    }

    static void main(String[] args) {
        double lon1 = 121.324549;
        double lat1 = 31.210538;
        double lon2 = 121.322693;
        double lat2 = 31.201578;
        BigDecimal distance = calculateDistance(lat1, lon1, lat2, lon2);
        System.out.println("Distance between user and store: " + distance.doubleValue() + " km");
    }
}